import dialog from '@/common/utils/dialog.js'
class websocket {
	constructor(url) {
		this.token = '';
		this.url = url;
		this.socketTask = null;
	}
	
	onOpen(res){
		console.log('WebSocket连接已打开！');
	}
	
	onMessage(data){
		console.log('WebSocket收到一个消息！',data);
		var jsondata = JSON.parse(data.data);
		if(jsondata.Category == 1){
			uni.$emit('order-update',{
				type: 'update',
				orderId: jsondata.ObjectId
			});
		}else if(jsondata.Category == 2){
			dialog.dialogMsg('您的账号在其他地方登录');
		}else{
			dialog.dialogMsg(jsondata.Content);
		}
	}
	
	onClose(res){
		this.close();
		console.log('WebSocket 已关闭！');
	}
	
	onError(err){
		console.error('WebSocket连接打开失败，请检查！');
	}
	
	connect(token){
		console.log('connect.websocket',this)
		let that = this;
		that.token = token;

		// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
		that.socketTask = uni.connectSocket({
			header:{
				'Access-Token': that.token,
				'content-type': 'application/json'
			},
			// #ifdef H5
			url: that.url + `?AccessToken=${that.token}`,
			// #endif
			// #ifndef H5
			url: that.url,
			// #endif
			fail:function(res){
				console.log("连接服务器websocket_失败",res);
			},
			success:function(res){
				console.log("连接服务器websocket_成功",res);
			},
			complete:function(res){
				console.log("连接服务器websocket_完成",res);
			}
		});
		//监听 WebSocket 连接打开事件
		that.socketTask.onOpen(res=>{
			that.onOpen(res);
		})
		//监听 WebSocket 接受到服务器的消息事件
		that.socketTask.onMessage(res=>{
			that.onMessage(res);
		})
		//监听 WebSocket 连接关闭事件
		that.socketTask.onClose(res=>{
			that.onClose(res);
		})
		//监听 WebSocket 错误事件
		that.socketTask.onError(res=>{
			that.onError(res);
		})
	}
	
	close(){
		this.token = '';
		if(this.socketTask == null)
			return;
		this.socketTask.close();
		this.socketTask = null;
	}
	
	sendMessage(data){
		this.socketTask.send({
			data: data,
			success(res) {
				console.log('消息发送成功')
			},
			fail(err) {
				console.log('消息发送失败')
			},
			complete(res) {
				
			}
		})
	}
}

export function createSocket(params){
	return new websocket(params.url)
}